package com.liuwei.classy.service.bizimpl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.liuwei.classy.dao.PaperMapper;
import com.liuwei.classy.model.Pagination;
import com.liuwei.classy.model.Paper;
import com.liuwei.classy.model.Shiti;
import com.liuwei.classy.model.UserPaperStat;
import com.liuwei.classy.service.bizinter.IPaperService;
import com.liuwei.classy.util.pub.tool.StringUtils;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by qingshengzheng on 17/11/18.
 */
@Service
@CacheConfig(cacheNames = "paper")
public class PaperServiceImpl implements IPaperService {
    @Autowired
    private PaperMapper paperMapper;

    @Resource(name = "esclinet")
    private Client esclient;

    @Override
    public Paper getPaperByid(String id) {
        Paper paper = paperMapper.getPaper(id);
        List<String> aids = paperMapper.aidsOfPaper(id);
        if(paper!=null&&aids!=null&&!aids.isEmpty()) {
            paper.setAids(aids);
        }
        return paper;

    }

    @Override
    @CachePut(value = "paper", key = "'COLLECT_PAPER:'+#p0+':'+#p1")
    public int collectPaper(Long uid, String pid) {
        Long time = System.currentTimeMillis();
        paperMapper.collectPaper(uid, pid, time);
        return 0;
    }

    @Override
    public int collectShiti(Long uid, String pid) {
        paperMapper.collectShiti(uid, pid);
        return 0;
    }

    @Override
    public List<Paper> getCollectPaper(Long uid, Pagination<Paper> page) {
        PageHelper.startPage(page.getPageNo(), 1);
        List<String> pids = paperMapper.getCollectPapers(uid);
        List<Paper> papers = new ArrayList<Paper>();
        for (String pid : pids) {
            Paper paper = getPaperByid(pid);
            papers.add(paper);
        }
        return papers;
    }

    @Override
    @Cacheable(value = "papercache", key = "#root.cache[0].name+':'+uid")
    public String getPaperTitle(String pid) {
        Paper paper = paperMapper.getPaper(pid);
        return paper.getPapername();
    }

    @Override
    public List<Paper> getRmdPapers(Long uid, Pagination<Paper> papers) {
        return null;
    }

    @Override
    public List<Paper> filterPaper(Long uid, Paper paper, Pagination<Paper> page) {
        List<Paper> vs = new ArrayList<Paper>();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from(page.getStart());
        searchSourceBuilder.size(page.getPageSize());
        SearchRequestBuilder request = esclient.prepareSearch("paper").setTypes("papertype");
        request.setFrom(page.getStart());
        request.setSize(page.getPageSize());
        request.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
        QueryBuilder qb = combEsPaperQuery(paper);
        request.setQuery(qb);
        SearchResponse response = request.execute().actionGet();
        for (SearchHit hit : response.getHits()) {
            String jonStr = hit.getSourceAsString();
            Paper temp = JSON.parseObject(jonStr, Paper.class);
            vs.add(temp);
        }
        return vs;
    }

    public QueryBuilder combEsPaperQuery(Paper paper) {
        BoolQueryBuilder qb = new BoolQueryBuilder();
        if (!StringUtils.isNull(paper.getPapername()))
            qb.should(QueryBuilders.termQuery("papername", paper.getPapername()));
        if (!StringUtils.isNull(paper.getGrade()))
            qb.filter(QueryBuilders.termQuery("grade", paper.getGrade()));
        if (!StringUtils.isNull(paper.getPaperyear()))
            qb.filter(QueryBuilders.termQuery("paperyear", paper.getPaperyear()));
        return qb;
    }

    @Override
    public Shiti getShitiByid(String id) {
        return paperMapper.getShitiById(id);
    }

    @Override
    public List<Shiti> getShitiOfPaper(String pid) {
        List<Shiti> shitis = paperMapper.shitisOfPaper(pid);
        return shitis;
    }

    @Override
    public List<Shiti> getCollectShiti(Long uid, Pagination<Shiti> page) {
        List<Shiti> papers = paperMapper.getCollectShitis(uid, page.getPageNo(), page.getPageSize());
        return papers;
    }

    @Override
    public List<Paper> historyPaper(Long uid, Pagination<Paper> page) {
        List<Paper> papers = paperMapper.historyPapers(uid, page.getPageNo(), page.getPageSize());
        return papers;
    }

    @Override
    public UserPaperStat getUserPaperStat(Long uid) {
        UserPaperStat stat = new UserPaperStat();
        return stat;
    }
}
